<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


class TeamModel extends Model
{

	/**
	 * Team Leader判断
	 *
	 * @param int $TeamID
	 * @param int $userID
	 * @return bool
	 */
	public function isTeamLeader($teamID, $userID)
	{
		$map = array(
			'team_id' => $teamID,
			'leader_id' => $userID,
			'status' => 1,
		);
		$count = $this->where($map)->count();
		return intval($count) < 1 ? false : true;  
	}
	
	
	/**
	 * 获取用户创建的团队数
	 * 
	 * @param int $userID
	 * @return int
	 */
	public function getUserTeamCount($userID)
	{
		$map = array(
			'leader_id' => $userID,
			'status' => 1,
		);
		$count = $this->where($map)->count();
		return intval($count);
	}
	
	
	/**
	 * 获取团队名
	 * 
	 * @param int $teamID
	 * @return string
	 */
	public function getTeamNameByID($teamID)
	{
		$map = array('team_id' => $teamID);
		return $this->where($map)->getField('name');
	}
	
	
	/**
	 * 更新团队成员计数
	 * 
	 * @param int $teamID
	 * @return mix
	 */
	public function updateUserCount($teamID)
	{
		$TeamUser = D('TeamUser');
		$userCount = $TeamUser->getTeamUserCount($teamID);
		$where = array('team_id' => $teamID);
		$this->where($where)->setField('user_count', $userCount);
	}
	
	
	/**
	 * 更新团队积分
	 * 
	 * @param int $teamID
	 * @param int $points
	 * @return mix
	 */
	public function updatePointCount($teamID, $points)
	{
		if ($points > 0)
		{
			$this->setInc('point_count', 'team_id='.$teamID, abs($points));
		}
		else
		{
			$this->setDec('point_count', 'team_id='.$teamID, abs($points));
		}
	}
	
	
	/**
	 * 缓存团队明星队员
	 *
	 * @param int $teamID
	 * @param int $limit
	 * @param int $expired
	 * @return null
	 */
	public function cacheTopTeamUsers($teamID, $limit=10, $expired=3600)
	{
        $limit   = !empty($limit) ? intval($limit) : 10;
		$expired = !empty($expired) ? intval($expired) : 60 * 60;
        
		$name   = 'cache_top_team_users_'.$teamID;
		$prefix = $this->tablePrefix;
    	$where  = " team_id={$teamID} AND is_best=0 ";

        $sql  = " SELECT user_id,username,email,point_count,COUNT(poster_id) AS best_answer_count ";
    	$sql .= " FROM {$prefix}answer A LEFT JOIN {$prefix}user U ON A.poster_id=U.user_id ";
    	$sql .= " WHERE {$where} ";
    	$sql .= " GROUP BY poster_id ORDER BY best_answer_count DESC LIMIT {$limit} ";

    	$users = $this->query($sql);
    	S($name, $users, $expired);
	}
	
	
	/**
	 * 获取团队明星队员
	 *
	 * @param int $teamID
	 * @param int $limit
	 * @return array
	 */
	public function getTopTeamUsers($teamID)
	{
        $name  = 'cache_top_team_users_'.$teamID;
        $users = S($name);
        if (empty($users))
	    {
			$this->cacheTopTeamUsers($teamID);
	    	$users = S($name);
	    }
	    return $users;
	}
	
}

/* End of file TeamModel.class.php */
/* Location: ./App/Lib/Model/TeamModel.class.php */